<template>
  <div>
    <el-dialog width="80%" :visible.sync="dialogVisible" @close="onClose" :title="title">
      <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="250px"
               label-position="left">
        <el-form-item label="QQ群号码" prop="number">
          <el-input v-model="formData.number" placeholder="请输入QQ群号码"></el-input>
        </el-form-item>
        <el-form-item  label="QQ群号二维码" prop="avatarUrl">
          <ImageUpload v-model="formData.avatarUrl" :limit="1"/>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>

import {updateMainQQ} from "@/api/user/user"

export default {
  data() {
    return {
      dialogVisible: false,
      title: '编辑',
      formData: {
        number: undefined,
        avatarUrl: undefined
      },
      rules: {
        number: [{
          required: true,
          message: '请输入QQ群号码',
          trigger: 'blur'
        }],
        avatarUrl:[{
          required: true,
          message: '请上传图片',
          trigger: 'blur'
        }],
      },
      id: null
    }
  },

  methods: {
    // 弹窗
    async onOpen(obj) {
      if (obj) {
        this.id = true
        this.title = "编辑"
        this.formData = JSON.parse(JSON.stringify(obj))
        console.log('formData:',this.formData)
      } else {
        this.id = false
        this.title = "新增"
      }
      this.dialogVisible = true
    },
    onClose() {
      this.dialogVisible = false
      this.$refs['elForm'].resetFields()
      this.formData.number = undefined
      this.formData.avatarUrl = undefined
    },
    close() {
      this.dialogVisible = false
    },
    // 提交数据
    handleConfirm() {
      this.$refs['elForm'].validate(async valid => {
        this.loading = true
        if (!valid) {
          // 如果验证不通过，则阻止后续代码执行
          this.loading = false;
          return;
        }
        if (this.id) {
          try {
            // 编辑
            await updateMainQQ(this.formData)
            this.$message({
              message: '修改成功',
              type: 'success'
            });
            this.$emit('success')
            this.onClose()
            this.loading = false
          } catch (error) {
            this.loading = false
          }
        } else {
          try {
            // 新增
            await updateMainQQ(this.formData)
            this.$message({
              message: '新增成功',
              type: 'success'
            });
            this.$emit('success')
            this.onClose()
            this.loading = false
          } catch (error) {
            this.loading = false
          }
        }
      })
    },
  }
}

</script>
<style>
.el-upload__tip {
  line-height: 1.2;
}

</style>
